package manager;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.DBManager;
import common.TableManager;
//import javax.swing.JFrame;
//import javax.swing.JOptionPane;

public class DeleteServlet extends HttpServlet
{
	Connection connection=null;
	Statement statement=null;
	private String resultMessage=null;
//	private String result=null;
//	private int dialogType;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		//super.doGet(req, resp);
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=UTF-8");
		deleteInfo(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		//super.doPost(req, resp);
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html; charset=UTF-8");
		deleteInfo(req,resp);
	}

	protected void deleteInfo(HttpServletRequest req, HttpServletResponse resp)
	{
		connection=DBManager.getConnection();

		int flag;
		String indexId=req.getParameter("id");
		ManagerBean targetInfo=(ManagerBean)TableManager
												.getRecord(TableManager.MANAGERS_TABLE, Integer.parseInt(indexId))
												.getBean();
		if(targetInfo.isDeleteFlag())
		{
			flag=0;
		}
		else
		{
			flag=1;
		}

		try
		{
			statement=connection.createStatement();
			statement.executeUpdate("UPDATE managers SET DELETE_FLAG="+flag+" WHERE ID="+targetInfo.getId());
//			result="削除完了";
			resultMessage="削除しました";
//			dialogType=JOptionPane.INFORMATION_MESSAGE;
		}
		catch (SQLException e)
		{
			System.out.println(e);
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
		finally
		{
			if(statement!=null)
			{
				try
				{
					statement.close();
				}
				catch (SQLException e)
				{
					e.printStackTrace();
				}
			}

			if(connection!=null)
			{
				try
				{
					connection.close();
				}
				catch (SQLException e)
				{
					e.printStackTrace();
				}
			}

//			if(resultMessage==null)
			{
//				result="削除失敗";
//				resultMessage="削除に失敗しました";
//				dialogType=JOptionPane.ERROR_MESSAGE;
			}

//			JFrame frame = new JFrame();
//			JOptionPane.showMessageDialog(frame, resultMessage, result, dialogType);

			req.setAttribute("msg", resultMessage);

			RequestDispatcher requestDispather=req.getRequestDispatcher("/manager/ListServlet");

			try
			{
				requestDispather.forward(req, resp);
			}
			catch (ServletException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}
}
